package com.luoqy.speedy.modular.api.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.luoqy.speedy.core.cache.CacheService;
import com.luoqy.speedy.core.cache.CacheServiceImpl;
import com.luoqy.speedy.data.DataBase;
import com.luoqy.speedy.data.MySqldbUtil;
import com.luoqy.speedy.modular.web.dao.FictionDto;
import com.luoqy.speedy.modular.web.model.Chapter;
import com.luoqy.speedy.modular.web.model.ChapterContent;
import com.luoqy.speedy.modular.web.model.Fiction;
import com.luoqy.speedy.modular.web.service.IChapterContentService;
import com.luoqy.speedy.modular.web.service.IChapterService;
import com.luoqy.speedy.modular.web.service.IFictionService;
import com.luoqy.speedy.modular.web.service.IFictionShelfService;
import com.luoqy.speedy.modular.web.utils.ClassUtil;
import com.luoqy.speedy.modular.web.vo.FictionVo;
import com.luoqy.speedy.modular.web.vo.LayuiPage;
import com.luoqy.speedy.util.Result;

@RestController
@RequestMapping("/api")
public class H5Controller {
	@Autowired
	private IFictionService iFictionService;
	@Autowired
	private IChapterService iChapterService;
	@Autowired
	private IChapterContentService iChapterContentService;
	@Autowired
	private IFictionShelfService iFictionShelfService;
	public static void main(String[] args) {
		System.err.println(Math.random());
		for (int i = 0; i < 9; i++) {
			System.out.println((int)(Math.random()*1200));
		}
		
	}
	/**
	 * 推荐书单
	 * @return
	 */
	@RequestMapping("/recommend")
	public Result recommendFiction(int page){
		Result result=new Result();
		page=page*12;
		List<Map<String,Object>> list=(List<Map<String, Object>>) MySqldbUtil.mysqlSelect("select *,(select count(id) from fiction) count from fiction limit "+page+",12", "list",new DataBase());
		if(list.size()>0){
			List<Map<String,Object>> listData=new ArrayList<Map<String,Object>>();
			//可能会存在重复的随机数
			int size=12;
			if(list.size()<12)size=list.size();
			for (int i = 0; i < size; i++) {
				Map<String,Object> data = list.get(i);
				Map<String,Object> chapter=(Map<String, Object>) MySqldbUtil.mysqlSelect("select min(id) newsid,chapter_title newsname  from chapter where fiction_id="+data.get("id"),"none",new DataBase());
				data.put("newsid",chapter.get("newsid"));
				data.put("newsname",chapter.get("chapter_title"));
				listData.add(data);
			}
			result.setState(1);;
			result.setData(listData);
			result.setMessage("分页推荐成功");
		}else{
			result.setState(0);
			result.setData(list);
			result.setMessage("没有数据");
		}
		
		return result;
	}
	/**
	 * 书籍列表
	 * @param fictionVo
	 * @return 
	 */
	@RequestMapping("/list")
	public Map<String,Object> listbook(FictionVo fictionVo){
		Map<String,Object> result=new HashMap<String,Object>();
		long curr = fictionVo.getCurr();
        long limit = fictionVo.getLimit();
        Map<String,String> map=new HashMap<>();
        map= ClassUtil.setConditionMap(fictionVo,new FictionDto());
        LayuiPage<Fiction>  layuiPage = iFictionService.selectPage(curr, limit,map);
        fictionVo.setCount(layuiPage.getTotal());
        result.put("list",layuiPage.getList());
        result.put("parameter",fictionVo);
        return result;
	}
	/** 
	 * 查询书籍内容
	 * @param id
	 * @return
	 */
	@RequestMapping("/searchDetail")
    public Map<String,Object>  searchDetail(String id) {
    	Map<String,Object> result=new HashMap<String,Object>();
    	//内容
    	Chapter chapter=iChapterService.getById(id);
    	
    	if(null==chapter){
    		result.put("state",0);
    		result.put("data",chapter);
    		result.put("message","不存在的数据");
    	}else{
    		ChapterContent data = iChapterContentService.getById(chapter.getContentId());
    		result.put("state",1);
    		//去除转行符
    		if(null!=data&&null!=data.getContent()){
    			String content=data.getContent();
        		do {
        			content=content.substring(0,content.length()-4);
    			} while (content.substring(content.length()-4).contains("br"));
        		data.setContent(content);
    		}
    		result.put("data",data);
    		result.put("message","查询成功");
    	}
    	return result;
    }
	
	/**
	 * 根据ID查询书籍信息
	 * @param id
	 * @return
	 */
	@RequestMapping("/searchbookById")
    public Map<String,Object>  searchbookById(String id) {
		System.out.println(id);
    	Map<String,Object> result=new HashMap<String,Object>();
    	//书籍信息
    	Fiction data = iFictionService.getById(id);
    	
    	
    	if(null==data){
    		result.put("state",0);
    		result.put("data",data);
    		result.put("message","不存在的书籍");
    	}else{
    		//书籍目录
    		List<Chapter> listData=iChapterService.queryByFictionIdList(Integer.valueOf(id));
    		result.put("state",1);
    		result.put("data",data);
    		result.put("listdata",listData);
    		result.put("message","查询成功");
    	}
    	return result;
    }
	/**
     * 小说列表简要查询
     *
     */
    @RequestMapping("/searchbook")
    public Map<String,Object>  search( FictionVo fictionVo) {
    	Map<String,Object> result=new HashMap<String,Object>();
        String fictionName = fictionVo.getFictionName();
        result.put("fictionName",fictionName);
        List<Fiction> list = iFictionService.queryLike(fictionName);
        result.put("list",list);
        return result;
    }
    /**
     * 查询云端用户单本阅读记录
     * @param phone 
     * @param id
     * @return
     */
    @RequestMapping("/findOneBookCase")
    public Result findOneBookCase(String phone,int id){
    	CacheService cache=new CacheServiceImpl();
    	Result result=new Result();
    	if(cache.isContains("h5user"+phone)){
	    	Map<String,Object> h5user=(Map<String, Object>) cache.getCacheDataByKey("h5user"+phone);
	    	String sql="select fs.id id,fs.page page,fs.indexs 'index',fs.fiction_id fiction_id,fs.chapter_id news, "
					+ "f.fiction_name title,f.img_url img,c.chapter_title name "
					+ "from fiction_shelf fs left join fiction f left join chapter c "
					+ "on fs.chapter_id=c.id "
					+ "on fs.fiction_id=f.id "
					+ "where fs.fiction_id="+id
					+" and userid="+h5user.get("id");
	    	Object data=MySqldbUtil.mysqlSelect(sql, "none",new DataBase());
	    	if(null!=data){
	    		result.setData(data);
	    		result.setMessage("查询成功");
	    		result.setState(1);
	    	}else{
	    		result.setData(data);
	    		result.setMessage("查询成功");
	    		result.setState(0);
	    	}
	    	
    	}else{
    		result.setData(new String[0]);
    		result.setMessage("没有登录");
    		result.setState(0);
    	}
    	return result;
    }
    /**
     * 查询云端用户书架列表
     * @param page 页码
     * @param phone 账号
     * @return
     */
    @RequestMapping("/bookcaselist")
    public Result searchBookCase(Integer page,String phone){
    	Result result=new Result();
    	CacheService cache=new CacheServiceImpl();
    	if(cache.isContains("h5user"+phone)){
    		if(null==page){
    			page=0;
    		}
    		int pageSize=60;
    		page=page*pageSize;
    		Map<String,Object> h5user=(Map<String, Object>) cache.getCacheDataByKey("h5user"+phone);
    		String sql="select fs.id id,fs.page page,fs.indexs 'index',fs.fiction_id fiction_id,fs.chapter_id news, "
    				+ "f.fiction_name title,f.img_url img,c.chapter_title name "
    				+ "from fiction_shelf fs left join fiction f left join chapter c "
    				+ "on fs.chapter_id=c.id "
    				+ "on fs.fiction_id=f.id "
    				+"where userid="+h5user.get("id")+" limit "+page+","+pageSize;
    		Object list=MySqldbUtil.mysqlSelect(sql, "list",new DataBase());
    		result.setData(list);
    		result.setMessage("查询成功");
    		result.setState(1);
    	}else{
    		result.setData(new String[0]);
    		result.setMessage("没有登录");
    		result.setState(0);
    	}
    	return result;
    }
    /**
     * 用户加入云端书架，保证云端适用
     * @param req
     * @param phone 用户账号/手机号
     * @param id 书籍ID
     * @param page 页码
     * @param index 页标
     * @return
     */
    @RequestMapping("/addBookcase")
    public Result addBookcase(HttpServletRequest req,String phone,int id,int page,int index,int news) {
    	Result result=new Result();
    	CacheService cache=new CacheServiceImpl();
    	if(cache.isContains("h5user"+phone)){
    		Map<String,Object> h5user=(Map<String, Object>) cache.getCacheDataByKey("h5user"+phone);
    		Object data=MySqldbUtil.mysqlSelect("select id from fiction_shelf where user_id="+h5user.get("id")+" and fiction_id="+id, "none",new DataBase());
    		if(null==data){
    			String executeSql="insert into fiction_shelf set user_id="+h5user.get("id")+",fiction_id="+id+",page="+page+",indexs="+index+",chapter_id="+news;
        		int state=MySqldbUtil.mysqlExecute(executeSql,new DataBase());
        		if(state==0){
        			result.setData(null);
            		result.setMessage("加入云端记录失败");
            		result.setState(1);
        		}else{
        			result.setData(null);
            		result.setMessage("加入云端记录成功");
            		result.setState(1);
        		}
    		}else{
    			String executeSql="update fiction_shelf set page="+page+",indexs="+index+",chapter_id="+news+" where user_id="+h5user.get("id")+" and fiction_id="+id;
        		int state=MySqldbUtil.mysqlExecute(executeSql,new DataBase());
        		if(state==0){
        			result.setData(null);
            		result.setMessage("更新云端记录失败");
            		result.setState(1);
        		}else{
        			result.setData(null);
            		result.setMessage("更新云端记录成功");
            		result.setState(1);
        		}
    		}
    		
    	}else{
    		result.setData(null);
    		result.setMessage("没有登录");
    		result.setState(0);
    	}
        return result;
    }
}
